package com.dq.controller.api.merchant.message;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.MessageQuery;
import com.dq.vo.Vo;

import com.dq.domain.message.oneself.InstructionMessage;
import com.dq.domain.message.oneself.Message;
import com.dq.domain.message.oneself.centre.ApprovalUserCentre;
import com.dq.domain.message.oneself.centre.InstructionStaffuserCentre;
import com.dq.domain.message.oneself.info.InstructionMessageReturn;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.BeanNullUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cf
 */
@Api(description = "门店消息通用方法")
@RestController
@RequestMapping("/api/message/")
public class AppMessageController extends AllService {

    @ApiOperation("消息查看")
    @GetMapping("/look/{id}/{type}")
    public Vo updateType(@PathVariable @ApiParam(value = "消息ID") Long id, @PathVariable @ApiParam(value = "返给页面【messageTypeEn】字段值") String type) throws AdminException {

        messageService.look(id, type);

        return new Vo(HttpStatus.OK);
    }

    /**
     * app/pc通用
     * @param messageQuery
     * @return
     * @throws AdminException
     */
    @ApiOperation("获取员工/门店/boss所有消息类型列表")
    @PostMapping("/list")
    public Vo list(@ApiParam("[messageType: (all: 所有类型)], [type: (user员工端调用， org门店调用，这里orgId可以不传, boss: boss调用，可以根据门店搜索)]") @RequestBody MessageQuery messageQuery) throws AdminException {
        if(messageQuery.getMessageType() == null) {
            throw new AdminException("请选择消息类型");
        }
        if(messageQuery.getType() == null) {
            throw new AdminException("请选择搜索范围");
        }
        SysUser user = sysUserService.getUser();
        if(messageQuery.getType().name.equals(MessageQuery.Type.org.name)) {
            if(messageQuery.getOrgId() == null) {
                if(user.getSection() == null) {
                    throw new AdminException("门店id为空");
                }
                messageQuery.setOrgId(user.getSection().getId());
            }
        }

        messageQuery.format();
        Map<String, Object> query = messageQuery.parseMap();
        String theme = null;
        if(StringUtils.isNotBlank(messageQuery.getTheme())) {
            theme = "%" + messageQuery.getTheme() + "%";
        }

        List<Object> returnJson = new ArrayList<>();

        List<Integer> messageTypes = getIntegers(messageQuery.getMessageType().name);

        List<Message> messageList = messageService.messageListSql(messageQuery.getType().toString(), theme, messageTypes, user.getId(), messageQuery.getOrgId(), messageQuery.getBeginSearchTime(), messageQuery.getEndSearchTime(), messageQuery.getPage(), messageQuery.getSize());
        Long count = messageService.messageCountSql(messageQuery.getType().toString(), theme, messageTypes, user.getId(), messageQuery.getOrgId(), messageQuery.getBeginSearchTime(), messageQuery.getEndSearchTime());
        for (Message message : messageList) {
            if(message.getMessageType().name.equals(Message.MessageType.instruction.name)) {
                // 指令
                Map<String, Object> query01 = new HashMap<>(16);
                query01.put("instructionMessage_id", message.getId());
                List<InstructionStaffuserCentre> centreList = dao.find(dao.query2Hql(InstructionStaffuserCentre.class, query01), query01);
                InstructionMessage instructionMessage = (InstructionMessage) message;
                if(messageQuery.getType().name.equals(MessageQuery.Type.boss.name)) {
                    // 返回所有
                    returnJson.add(instructionMessage.toJson(centreList, null, null));
                }else {
                    // 返回自己的回复
                    returnJson.add(instructionMessage.toJson(centreList, user.getId(), null));
                }
            }
            else if(message.getMessageType().name.equals(Message.MessageType.approval.name)) {
                // 审批
                Map<String, Object> query01 = new HashMap<>(16);
                query01.put("approvalMessage_id", message.getId());
                query01.put("caseUser_id", user.getId());
                List<ApprovalUserCentre> approvalUserCentres = dao.find(dao.query2Hql(ApprovalUserCentre.class, query01), query01);
                if(approvalUserCentres.size() != 0){
                    returnJson.add(approvalUserCentres.get(0).toVO());
                }
            }
            else {
                returnJson.add(message.toVO());
            }
        }

        PageHelper.startPage(messageQuery.getPage(), messageQuery.getSize());
        PageInfo pageInfo = new PageInfo(returnJson);
        pageInfo.setTotal(count);

        return new Vo(pageInfo);
    }


    @ApiOperation("员工回复 boss指令")
    @PostMapping("/reply/{instructionId}")
    public Vo list(@ApiParam("boss指令ID") @PathVariable Long instructionId, @RequestBody InstructionMessageReturn instructionMessageReturn) throws AdminException {

        InstructionMessage instructionMessage = dao.get(InstructionMessage.class, instructionId);
        if(instructionMessage == null) {
            throw new AdminException("无对应id对象");
        }
        instructionMessageReturn.setInstructionMessage(instructionMessage);

        HashMap<String, Object> query = new HashMap<>(16);
        query.put("createUser_id", sysUserService.getUser().getId());
        query.put("instructionMessage_id", instructionMessageReturn.getInstructionMessage().getId());
        List<InstructionMessageReturn> menuList = dao.find(dao.query2Hql(InstructionMessageReturn.class, query), query);
        if(menuList != null && menuList.size() > 0) {
            InstructionMessageReturn messageReturn = menuList.get(0);
            BeanUtils.copyProperties(instructionMessageReturn, messageReturn, BeanNullUtil.getNullPropertyNames(instructionMessageReturn));
            instructionMessageReturnService.update(messageReturn);
        }else {
            instructionMessageReturnService.save(instructionMessageReturn);
        }
        return new Vo(HttpStatus.OK);
    }


    public List<Integer> getIntegers(String messageTypeName) {
        List<Integer> messageTypes = new ArrayList<>();
        Message.MessageType[] messageTypeList = Message.MessageType.values();

        if(messageTypeName.equals(Message.MessageType.all.name)) {
            // todo no
            for (Message.MessageType messageType : messageTypeList) {
                messageTypes.add(messageType.ordinal());
            }
        }else {
            for (Message.MessageType messageType : messageTypeList) {
                if(messageTypeName.equals(messageType.name)) {
                    messageTypes.add(messageType.ordinal());
                    break;
                }
            }
        }
        return messageTypes;
    }

}
